package cn.iocoder.yudao.core.init;

import cn.iocoder.yudao.common.core.StopWatch;
import cn.iocoder.yudao.core.thread.core.utils.FutureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 初始化数据
 */
@Component
@Slf4j
public class InitData implements ApplicationRunner {

    @Autowired
    private List<InitSerivce> initSerivces;

    @Autowired
    private ConfigurableApplicationContext context;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        if (context.isActive() && context.isRunning()) {
            this.load();
        }

    }

    private void load() {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start("执行初始化数据");

        CompletableFuture<?>[] futures = initSerivces.stream()
                .map(initSerivce -> FutureUtils.runAsync(initSerivce::init)).toArray(CompletableFuture[]::new);
        FutureUtils.join(futures);

        for (CompletableFuture<?> future : futures) {
            if (future.isCompletedExceptionally()) {
                throw new RuntimeException("执行初始化发生异常，请排查");
            }
        }

        stopWatch.stop();
        log.info(stopWatch.prettyPrint(TimeUnit.MILLISECONDS));

    }


}
